import React, { useState,useEffect, useMemo ,useRef} from 'react';
import {ProgressCircle, Space ,Modal,CapsuleTabs, Button} from 'antd-mobile'
import BillList from '../../components/BillList'
// import BucketList from '../../components/BucketList';
import './index.css'; // 引入样式文件
import { EditFill } from 'antd-mobile-icons';
import PopupAddBills from '../../components/PopupAddBills';
import dayjs from 'dayjs'
import { request } from '../../utils';
import { Cascader } from 'antd-mobile';
import Voice from '../../components/Voice'
const Moneybox = () => {
  const now = new Date()
  const nowyear = now.getFullYear()
  const [id, setId] = useState('')
  const [amount, setAmount] = useState(0)
  const [time, setTime] = useState(dayjs(now).format('YYYY-MM-DD HH:mm:ss'))
  const [visible, setVisible]=useState(false)
  const [billlist, setBilllist] = useState([])
  const [isfilled, setIsFilled] = useState(true)
  const [currentPage, setCurrentPage] = useState(0)
  const [hasMore, setHasMore] = useState(true)
  const pageSize = 10
  const [datevisible, setDatevisible] = useState(false)
  const [data, setData] = useState({year: new Date().getFullYear(), month: null, date: null })
  const [date, setDate] = useState(nowyear+'年')
  const latestDataRef = useRef(data)
  const latestHasmoreRef = useRef(hasMore)
  const [balance, setBalance] = useState(0); // 初始值为0

  useEffect(() => {
    const fetchBalance = async () => {
      try {
        const res = await request.get('/api/auth/balance');
        setBalance(res.balance); // 假设API返回的数据在res.data中
      } catch (error) {
        setBalance(0); // 出错时设为0
      }
    };
    fetchBalance();
  }, [data, isfilled,billlist]); // 依赖data和isfilled，确保在数据变化时重新获取余额
  useEffect(() => {
    latestDataRef.current = data
  }, [data])
  useEffect(() => {
    setCurrentPage(0)
    loadMore(true)
    
  }, [data])
  const options = useMemo(() => {
    // 生成年份选项（示例范围：当前年前后10年）
    const years = Array.from({ length: 10 }, (_, i) => {
      const year = new Date().getFullYear() - 9 + i
      return {
        label: `${year}年`,
        value: year,
        children: []
      }
    })
  
    // 生成月份选项
    years.forEach(yearObj => {
      if(yearObj.value == new Date().getFullYear()){
        const long = new Date().getMonth()+1
        yearObj.children = Array.from({ length: long }, (_, i) => {
          const month = i + 1
          return {
            label: `${month}月`,
            value: month,
            children: []
          }
        })
      }
      else{
        yearObj.children = Array.from({ length: 12 }, (_, i) => {
        const month = i + 1
        return {
          label: `${month}月`,
          value: month,
          children: []
        }
      })
    }
    })
  
    // 生成日期选项（动态计算天数）
    years.forEach(yearObj => {
      yearObj.children.forEach(monthObj => {
        if(monthObj.value == new Date().getMonth()+1 && yearObj.value == new Date().getFullYear()){
          monthObj.children = Array.from({ length: new Date().getDate() }, (_, i) => ({
            label: `${i + 1}日`,
            value: i + 1
          }))
        }else
        {const daysInMonth = new Date(yearObj.value, monthObj.value, 0).getDate()
        monthObj.children = Array.from({ length: daysInMonth }, (_, i) => ({
          label: `${i + 1}日`,
          value: i + 1
        }))}
      })
    })
  
    return years
  }, [])
  const newBill = useMemo(() => {
    return billlist.filter(item => 
      isfilled 
        ? item.bill_type.flow === 'income' 
        : item.bill_type.flow === 'outcome'
    )
  }, [isfilled, billlist, data])
  const loadMore = async (isReload = false) => {
    if (!latestHasmoreRef) return
    try {
      const nextPage = isReload ? 1 : currentPage + 1;
      const currentData = latestDataRef.current;
      const params = {
        year: currentData.year,
        month: currentData.month,
        date: currentData.date
    }
      const res = await request.get(`api/auth/bills/by-month?page=${nextPage}`,{params})
      if (isReload || billlist.length === 0) {
        setBilllist(res.data.data);
        setHasMore(res.data.data.length >= pageSize)
      } else {
        setBilllist(prev => [...prev, ...res.data.data]);
      }
      setHasMore(res.data.data.length >= pageSize)
      setCurrentPage(nextPage)
    } catch (e) {
      setHasMore(false)
      Modal.show({
        content: e.message,
        closeOnMaskClick: true,
      })
    }
  }
 
  return (
    <div className='month'>
      <div className="edit-icon" onClick={() => {
        setId('')
        setAmount('')
        setTime(dayjs(now).format('YYYY-MM-DD HH:mm:ss'))
        setVisible(true)
        }}>
        <EditFill fontSize={20} style={{marginTop: '15px'}}/>
        <div>记一笔</div>
      </div>
      <div  className='voice'>
      <Voice loadMore={loadMore}/>
      </div>
      
      <div className="month-container">
        <Space className='space' style={{ '--gap': '24px' }} align='center'>
          <ProgressCircle percent={60} style={{ '--size': '120px' , '--track-width': '8px', '--fill-color': '#20f4df' }}>
            <span className="large">60%</span>
          </ProgressCircle>
        </Space>
        <div className="month-save">
            <div>目前存款{balance}￥</div>
            <div>预算还剩10%</div>
          </div>
        <div className="price-item">
          <div className="price">123456789￥</div>
        </div>
      </div>
      <div className="bill-list" style={{
        position: 'sticky',
        top: 0,
        zIndex: 100,
        backgroundColor: '#f0f2f5',
        padding: '10px 0',
      }}>
        <div>
          <div style={{display:'flex',justifyContent:'space-between',backgroundColor:'#f0f2f5'}}>
            <div onClick={() => {
              setDatevisible(true)
              }}>{date}</div>
            <div>
              <Button fill={isfilled ? 'solid' : 'none'} color='warning' size='mini' onClick={() => {
                setIsFilled(true);
              }}>收入</Button>
              <Button fill={!isfilled ? 'solid' : 'none'} color='warning' size='mini' onClick={() => {
                setIsFilled(false);
              }}>支出</Button>
            </div>
          </div>
        </div>
      </div>

      
      <Cascader
            options={options}
            visible={datevisible}
            onClose={() => {
              setDatevisible(false)
            }}
            onConfirm={(value) => {
              const[year=null, month=null, date=null] = value
              setData({year, month, date})
              if(date){
              setDate(year+'年'+'-'+month+'月'+'-'+date+'日')
              }else if(month){
                setDate(year+'年'+'-'+month+'月')
              }else{
                setDate(year+'年')
              }}}
          />
      <div className="list"> 
        <BillList billlist={newBill} data={data} hasMore={hasMore} loadMore={loadMore}/>
      </div>
      
      <PopupAddBills visible={visible} setVisible={setVisible} now={now} id={id} setId={setId} amount={amount} setAmount={setAmount} time={time} setTime={setTime} loadMore={loadMore}/>
      
    </div>
  );
};

export default Moneybox;